<template>
  <el-dialog :title="!dataForm.id ? $t('Common.Add') : $t('Common.Edit')" :close-on-click-modal="false" :visible.sync="visible"
    @click="showCard = false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="auto">
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="dataForm.type">
          <el-radio v-for="(type, index) in dataForm.typeList" :label="index" :key="index">{{ type }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="dataForm.typeList[dataForm.type] + '名称'" prop="name">
        <el-input v-model="dataForm.name" :placeholder="dataForm.typeList[dataForm.type] + '名称'"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type === (0+2) || dataForm.type === (0+3) " :style="{position: 'relative'}" label="上级菜单"
        prop="parentName">
        <el-input v-model="dataForm.parentName" :readonly="true" placeholder="点击选择上级菜单" class="menu-list__input" @focus="showCard = !showCard"></el-input>
        <!-- update use card instead of pop on date 2019-09-19 by ouyuan  -->
        <el-card :style="{
                  position: 'absolute',
                  zIndex: '1000',
                  width: '100%',
                  height: '35vh',
                  overflow: 'scroll'}"
          v-show="showCard" class="box-card">
          <el-tree :data="menuList" :props="menuListTreeProps" node-key="menuId" ref="menuListTree" @current-change="menuListTreeCurrentChangeHandle"
            :default-expand-all="true" :highlight-current="true" :expand-on-click-node="false"></el-tree>
        </el-card>
        <!-- update 2019-09-19 end -->
      </el-form-item>
      <el-form-item v-if="dataForm.type === 1" label="上级目录" prop="parenttopId">
        <el-select v-model="dataForm.parenttopId" placeholder="请选择">
          <el-option v-for="item in allTopMenuList" :key="item.name" :label="item.name" :value="item.menuId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="dataForm.type === 0" label="展示方式" prop="childShowType">
        <el-radio-group v-model="dataForm.childShowType">
          <el-radio v-for="(type, index) in dataForm.showTypeList" :label="index" :key="index">{{ type }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="dataForm.type === (0+2)" label="菜单描述" prop="menuDesc">
        <el-input v-model="dataForm.menuDesc" placeholder="菜单描述"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type === (0) || dataForm.type === (0+2) " label="菜单路由" prop="url">
        <el-input v-model="dataForm.url" placeholder="菜单路由"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type !== (0+1)" label="授权标识" prop="perms">
        <el-input v-model="dataForm.perms" placeholder="多个用逗号分隔, 如: user:list,user:create"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type !== (2+1)" label="排序号" prop="orderNum">
        <el-input-number v-model="dataForm.orderNum" controls-position="right" :min="0" label="排序号"></el-input-number>
      </el-form-item>
      <el-form-item v-if="dataForm.type !== (2+1)" label="菜单图标" prop="icon">
        <el-row>
          <el-col :span="22">
            <el-popover v-if="dataForm.type !== (0+2)" ref="iconListPopover" placement="bottom-start" trigger="click"
              popper-class="mod-menu__icon-popover">
              <div class="mod-menu__icon-list">
                <el-button v-for="(item, index) in iconList" :key="index" @click="iconActiveHandle(item)" :class="{ 'is-active': item === dataForm.icon }">
                  <icon-svg :name="item"></icon-svg>
                </el-button>
              </div>
            </el-popover>
            <el-input v-model="dataForm.icon" v-popover:iconListPopover :readonly="dataForm.type === (0+2) ? false : true"
              placeholder="菜单图标名称" class="icon-list__input"></el-input>
          </el-col>
          <!-- <el-col :span="2" class="icon-list__tips">
                        <el-tooltip placement="top" effect="light">
                            <div slot="content">
                                全站推荐使用SVG Sprite, 详细请参考:
                                <a
                                    href="//github.com/daxiongYang/renren-fast-vue/blob/master/src/icons/index.js"
                                    target="_blank"
                                >icons/index.js</a>描述
                            </div>
                            <i class="el-icon-warning"></i>
                        </el-tooltip>
                    </el-col> -->
        </el-row>
      </el-form-item>

      <el-form-item v-if="dataForm.type === (0+2)" label="上传图标">
        <el-upload class="avatar-uploader" :action="uploadAction" :show-file-list="false" :on-success="handleAvatarSuccess">
          <img v-if="dataForm.icon" :src="dataForm.icon" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('Common.Cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmit()">{{ $t('Common.Confirm') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {
    treeDataTranslate
  } from "@/utils";
  import Icon from "@/icons";
  export default {
    data() {
      var validateUrl = (rule, value, callback) => {
        if (this.dataForm.type === 1 && !/\S/.test(value)) {
          callback(new Error("菜单URL不能为空"));
        } else {
          callback();
        }
      };
      return {
        uploadAction: '',
        visible: false,
        dataForm: {
          id: 0,
          parenttopId: '',
          type: 1,
          childShowType: 0,
          typeList: ["顶级目录", "目录", "菜单", "按钮"],
          showTypeList: ["分散式", "集中式", "多级菜单", "Tab切换"],
          name: "",
          menuDesc: "",
          parentId: 0,
          parentName: "",
          url: "",
          perms: "",
          orderNum: 0,
          icon: "",
          iconList: []
        },
        dataRule: {
          name: [{
            required: true,
            message: "菜单名称不能为空",
            trigger: "blur"
          }],
          parentName: [{
            required: true,
            message: "上级菜单不能为空",
            trigger: "change"
          }],
          url: [{
            validator: validateUrl,
            trigger: "blur"
          }]
        },
        allTopMenuList: [],
        menuList: [],
        menuListTreeProps: {
          label: "name",
          children: "children"
        },
        showCard: false
      };
    },
    created() {
      this.uploadAction = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`);
      this.iconList = Icon.getNameList();
    },
    methods: {
      handleAvatarSuccess(res, file) {
        console.log(file)
        console.log(res)
        if (res.code == 0) {
          this.dataForm.icon = res.url;
        } else {
          this.$message.error(res.msg);
        }
      },
      init(id) {
        Object.assign(this.dataForm, this.$options.data().dataForm)
        
        this.dataForm.id = id || 0;
        this.$http({
            url: this.$http.adornUrl("/sys/menu/select"),
            method: "get",
            params: this.$http.adornParams()
          })
          .then(({
            data
          }) => {
            this.menuList = treeDataTranslate(data.menuList, "menuId");
            this.allTopMenuList = data.allTopMenuList;
          })
          .then(() => {
            this.visible = true;
            this.$nextTick(() => {
              this.$refs["dataForm"].resetFields();
            });
          })
          .then(() => {
            if (!this.dataForm.id) {
              // 新增
              this.menuListTreeSetCurrentNode();
            } else {
              // 修改
              this.$http({
                url: this.$http.adornUrl(
                  `/sys/menu/info/${this.dataForm.id}`
                ),
                method: "get",
                params: this.$http.adornParams()
              }).then(({
                data
              }) => {
                this.dataForm.id = data.menu.menuId;
                this.$nextTick(() => {
                  this.dataForm.parenttopId = data.menu.parenttopId;
                });
                this.dataForm.type = data.menu.type + 1;
                this.dataForm.name = data.menu.name;
                this.dataForm.menuDesc = data.menu.menuDesc;
                this.dataForm.childShowType = data.menu.childShowType;
                this.dataForm.parentId = data.menu.parentId;
                this.dataForm.url = data.menu.url;
                this.dataForm.perms = data.menu.perms;
                this.dataForm.orderNum = data.menu.orderNum;
                this.dataForm.icon = data.menu.icon;
                this.menuListTreeSetCurrentNode();
              });
            }
          });

      },
      // 菜单树选中
      menuListTreeCurrentChangeHandle(data, node) {
        this.dataForm.parentId = data.menuId;
        this.dataForm.parentName = data.name;
        this.showCard = false
      },
      // 菜单树设置当前选中节点
      menuListTreeSetCurrentNode() {
        console.log(this.dataForm.parentId)
        this.$nextTick(() => {
          this.$refs.menuListTree.setCurrentKey(this.dataForm.parentId);
          this.dataForm.parentName = (this.$refs.menuListTree.getCurrentNode() || {})["name"];
        });
      },
      // 图标选中
      iconActiveHandle(iconName) {
        this.dataForm.icon = iconName;
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(
                `/sys/menu/${!this.dataForm.id ? "save" : "update"}`
              ),
              method: "post",
              data: this.$http.adornData({
                menuId: this.dataForm.id || undefined,
                parenttopId: this.dataForm.parenttopId,
                type: this.dataForm.type - 1,
                name: this.dataForm.name,
                menuDesc: this.dataForm.menuDesc,
                childShowType: this.dataForm.childShowType,
                parentId: this.dataForm.parentId,
                url: this.dataForm.url,
                perms: this.dataForm.perms,
                orderNum: this.dataForm.orderNum,
                icon: this.dataForm.icon
              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        });
      }
    }
  };
</script>

<style lang="scss">
  .mod-menu {

    .menu-list__input,
    .icon-list__input {
      >.el-input__inner {
        cursor: pointer;
      }
    }

    &__icon-popover {
      max-width: 370px;
    }

    &__icon-list {
      max-height: 180px;
      padding: 0;
      margin: -8px 0 0 -8px;

      >.el-button {
        padding: 8px;
        margin: 8px 0 0 8px;

        >span {
          display: inline-block;
          vertical-align: middle;
          width: 18px;
          height: 18px;
          font-size: 18px;
        }
      }
    }

    .icon-list__tips {
      font-size: 18px;
      text-align: center;
      color: #e6a23c;
      cursor: pointer;
    }
  }
</style>
